package com.lenovo.nova.util.network;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import com.lenovo.nova.util.debug.mylog;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.NetworkInfo;
import android.net.RouteInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.lenovo.nova.util.debug.MyOldLog;
import com.lenovo.nova.util.debug.RegexExpressUtil;
import com.lenovo.nova.util.debug.slog;

public class NetworkUtils {

	private static final String TAG = "NetworkUtils";
	public static final int CONNECTION_TYPE_WIFI = 0;
	public static final int CONNECTION_TYPE_CMNET = 1;
	public static final int CONNECTION_TYPE_WAP = 2;
	public static final int CONNECTION_TYPE_NO_CONNECT = 3;

	public static boolean validateDataFormat(String s) {
		log("-validateDataFormat===");
		if (null == s)
			return false;

		try {
			android.net.NetworkUtils.numericToInetAddress(s);
		} catch (IllegalArgumentException e) {
			return false;
		}

		Pattern pattern = Pattern
				.compile(RegexExpressUtil.CHECK_IP);

		Matcher matcher = pattern.matcher(s);

		return matcher.matches();
	}

	public static int getIntNumber(String IP) {
		InetAddress inetAddr = android.net.NetworkUtils.numericToInetAddress(IP);
		int IntNumber = android.net.NetworkUtils.inetAddressToInt((Inet4Address) inetAddr);
		return IntNumber;
	}

	public static boolean isNetworkConnected(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		if (info == null) {
			MyOldLog.e("network info is null", -1);
			return false;
		}
		return info.isConnected();
	}

	private static void log(String string) {
		Log.d(TAG, string);
	}

	public static InetAddress numericToInetAddress(String ipAddr) {
		return android.net.NetworkUtils.numericToInetAddress(ipAddr);
	}

	public static boolean isEtheConnect(Context mContext) {
		ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		if (info == null) {
			return false;
		}

		if (info.getType() == ConnectivityManager.TYPE_ETHERNET) {
			return true;
		}
		return false;
	}

	public static boolean isWifiConnect(Context mContext) {
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);

        WifiInfo info = wifiManager.getConnectionInfo();
		mylog.i(TAG,"isWifiConnect info is " + info);
		if (info == null) {
			return false;
		}

        try {
            List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
            for (int i= 0; i <configs.size();i++){
                WifiConfiguration config = configs.get(i);
                System.out.println(config.SSID + " " + config.linkProperties.getAddresses());

                if(config.linkProperties.getAddresses() != null){
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return false;
	}

	public static boolean isWEPPasswordInvalid(String paswd) {
		int length = paswd.length();
		String password = paswd.toString();
		// WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
		if (((length == 10 || length == 16 || length == 26 || length == 32 || length == 58) && password.matches("[0-9A-Fa-f]*")) || (length == 5 || length == 13)) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * if true , the IP configuration validate
	 * @param ipAddr
	 * @param prefixLength
	 * @param gateway
	 * @param dns1
	 * @param dns2
	 * @return
	 */
	public int isvalidateIpConfigFields(String ipAddr,String prefixLength,String gateway,String dns1,String dns2){
		LinkProperties linkProperties  = new LinkProperties();
		InetAddress inetAddr = null;
		try {
			inetAddr = NetworkUtils.numericToInetAddress(ipAddr);
			log("validateIpConfigFields get ip inetAddr = " + inetAddr);
			if (!NetworkUtils.validateDataFormat(inetAddr.getHostAddress())) {
				log("validateIpConfigFields ip is invalidate!!!");
				return "请输入有效的 IP 地址。".hashCode();
			}
		} catch (IllegalArgumentException e) {
			log("validateIpConfigFields get ip address error!!!");
			return "请输入有效的 IP 地址。".hashCode();
		}

		int networkPrefixLength = -1;
		try {
			log("validateIpConfigFields get length!!!");
			networkPrefixLength = Integer.parseInt(prefixLength);
		} catch (NumberFormatException e) {
			log("validateIpConfigFields get length error1!!!");
		}
		if (networkPrefixLength < 0 || networkPrefixLength > 32) {
			log("validateIpConfigFields get length error2!!!");
			return "请键入长度在 0 到 32 之间的网络前缀。".hashCode();
		}
		linkProperties.addLinkAddress(new LinkAddress(inetAddr, networkPrefixLength));

		InetAddress gatewayAddr = null;
		try {
			log("validateIpConfigFields get gateway!!!");
			gatewayAddr = NetworkUtils.numericToInetAddress(gateway);
			log("validateIpConfigFields get gateway = " + gatewayAddr);
			if (!validateDataFormat(gatewayAddr.getHostAddress())) {
				log("validateIpConfigFields gateway is invalidate!!!");
				return "请键入有效的网关地址。".hashCode();
			}
		} catch (IllegalArgumentException e) {
			log("validateIpConfigFields get gateway error!!!");
			return "请键入有效的网关地址。".hashCode();
		}
		linkProperties.addRoute(new RouteInfo(gatewayAddr));

		InetAddress dnsAddr = null;
		boolean dns1IsValid = true;
		String dns = dns1;
		try {
			log("validateIpConfigFields get dns1!!!");
			dnsAddr = NetworkUtils.numericToInetAddress(dns);
			log("validateIpConfigFields get dns1 = " + dnsAddr);
			if (!validateDataFormat(dnsAddr.getHostAddress())) {
				log("validateIpConfigFields dns1 is invalidate!!!");
				dns1IsValid = false;
			}
		} catch (IllegalArgumentException e) {
			log("validateIpConfigFields get dns1 error!!!");
			dns1IsValid = false;
		}
		if (dns1IsValid)
			linkProperties.addDns(dnsAddr);

		boolean dns2IsValid = true;
		if (dns2.length() > 0) {
			dns = dns2;
			try {
				log("validateIpConfigFields get dns2!!!");
				dnsAddr = NetworkUtils.numericToInetAddress(dns);
				if (!validateDataFormat(dnsAddr.getHostAddress())) {
					log("validateIpConfigFields dns2 is invalidate!!!");
					dns2IsValid = false;
				}
			} catch (IllegalArgumentException e) {
				log("validateIpConfigFields get dns2 error!!!");
				dns2IsValid = false;
			}
			if (dns2IsValid)
				linkProperties.addDns(dnsAddr);
		}
		if ((!dns1IsValid && dns1.length() > 0) || (dns1IsValid && !dns2IsValid) || (dns1.length() == 0 && !(dns2IsValid && dns2.length() > 0))) {
			return "请键入有效的 DNS 地址。".hashCode();
		}
		return 0;
	
	}
	
	
	public static void getClientPublicNetworkIPAddress(final Handler callback, final int msgWhat) {
		new Thread() {
			@Override
			public void run() {
				try {
					slog.p("NetWorkUtils getClientPublicNetworkIPAddress execute " + msgWhat);
					HttpClient client = new DefaultHttpClient();
					// Set the timeout in milliseconds until a connection is
					// established.
					BasicHttpParams httpParameters = new BasicHttpParams();
					// Set the default socket timeout (SO_TIMEOUT)
					// in milliseconds which is the timeout for waiting for
					// data.
					HttpConnectionParams.setConnectionTimeout(httpParameters, 2000);
					HttpConnectionParams.setSoTimeout(httpParameters, 2000);
					HttpGet request = new HttpGet("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json");
					request.setParams(httpParameters);
					HttpResponse response = null;
					try {
						slog.p("NetWorkUtils getClientPublicNetworkIPAddress begin get date from network ");
						response = client.execute(request);
					} catch (ExceptionInInitializerError e) {
						MyOldLog.e("Error : " + e);
						return;
					}

					int responseState = response.getStatusLine().getStatusCode();
					MyOldLog.p("responseState is " + responseState);

					if (responseState == HttpStatus.SC_OK) {
						String strResult = EntityUtils.toString(response.getEntity());
						JSONObject obj = new JSONObject(strResult);
						String ipStr = obj.getString("start");
						String province = new String(obj.getString("province"));
						String city = new String(obj.getString("city"));

						if (ipStr != null && !ipStr.equals("")) {
							MyOldLog.p("ipStr is " + ipStr);
						} else {
							MyOldLog.e("get ip error");
						}

						Message.obtain(callback, msgWhat, 0, 0, new String[] { province, city, ipStr }).sendToTarget();
					}
				} catch (Exception e) {
					MyOldLog.p("Get IP Error " + e.getMessage());
					e.printStackTrace();

				}
			}
		}.start();

	}

	
	   /**
     * 获取联网的类型
     *
     * @param context
     * @return
     */
    public static int getConnectType(Context context) {
            ConnectivityManager lcm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo.State wifi = lcm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

            if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
                    return CONNECTION_TYPE_WIFI;
            } else {
                    NetworkInfo.State mobile = lcm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
                    if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {

                            // 主apn的uri
                            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
                            Cursor mCursor = null;
							try {
								mCursor = context.getContentResolver().query(uri, null, null, null, null);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
                            try {
                                    if (mCursor != null) {

                                            // 游标移至第一条记录，当然也只有一条
                                            mCursor.moveToNext();
                                            String apn = mCursor.getString(mCursor.getColumnIndex("apn")).toLowerCase();
                                            if (apn != null && (apn.equals("3gnet") || apn.equals("cmnet") || apn.equals("uninet"))) {
                                                    return CONNECTION_TYPE_CMNET;
                                            } else {
                                                    String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                                                    if (proxyStr != null && proxyStr.trim().length() > 0) {
                                                            return CONNECTION_TYPE_WAP;
                                                    } else {
                                                            return CONNECTION_TYPE_CMNET;
                                                    }
                                            }
                                    }
                            } finally {
                            	if(mCursor != null){
                            		mCursor.close();
                            	}
                            }
                            return CONNECTION_TYPE_WAP;
                    }
            }
            return CONNECTION_TYPE_NO_CONNECT;

    }

    
    
}
